<template>
  <view>
    <view style="display: flex; justify-content: center; margin: 20rpx 0">
      <view style="width: 50%">
        <uni-segmented-control
          :current="current"
          :values="items"
          :style-type="styleType"
          :active-color="activeColor"
          @clickItem="onClickItem"
        />
      </view>
    </view>
    <view v-if="current === 0">
      <view class="form">
        <view class="form-content">
          <view class="form-item" @click="handleTap">
            <text class="label" style="color: red">*</text>
            <text class="label">危废行业俗称:</text>
            <text class="iptClass">{{
              memberStore.ApplyViewing.wfTypeName
            }}</text>
          </view>
          <view class="form-item" @click="handleDep">
            <text class="label">所属部门:</text>
            <text class="iptClass">{{
              memberStore.ApplyViewing.deptName
            }}</text>
          </view>
          <view class="form-item" @click="handledate">
            <text class="label" style="color: red">*</text>
            <text class="label">预计转移时间:</text>
            <text class="iptClass">{{
              memberStore.ApplyViewing.planTransTime
            }}</text>
          </view>
          <view
            class="form-item"
            @click="handlezhuanyun"
            v-if="props.transStatus == 4 || props.fromPage == 'homePage'"
          >
            <text class="label" style="color: red">*</text>
            <text class="label">危废明细</text>
            <text class="dianwo" v-if="!memberStore.ApplyViewing.wfIds"
              >请选择危废明细</text
            >
          </view>
          <!-- <view class="form-item">
            <text class="label">转移总量</text>
            <text class="iptClass">{{
              memberStore.ApplyViewing.wfTrans_Weight
            }}</text>
          </view> -->
          <view class="form-item">
            <text class="label" style="color: red">*</text>
            <text class="label">去向:</text>
            <input
              class="iptClass"
              type="text"
              v-model.trim="memberStore.ApplyViewing.transTo"
              :disabled="
                !(props.transStatus == 4 || props.fromPage == 'homePage')
              "
              placeholder="请输入去向"
            />
          </view>
          <ImageLogic
            :picturesPath="picturesPath"
            :isHide="props.transStatus == 1 || props.transStatus == 2"
            :isRequired="true"
          ></ImageLogic>
          <view class="form-item">
            <text class="label">备注:</text>
            <input
              class="iptClass"
              type="text"
              v-model.trim="memberStore.ApplyViewing.remark"
              :disabled="
                !(props.transStatus == 4 || props.fromPage == 'homePage')
              "
            />
          </view>
          <view class="form-item">
            <text class="label">申请人:</text>
            <text class="iptClass">{{ memberStore.userName }}</text>
          </view>
          <view class="form-item" v-show="props.transStatus != 4">
            <text class="label">流程:</text>
          </view>
          <view class="scrollClass" v-show="props.transStatus != 4">
            <view
              class="listsClass"
              v-for="(item, index) in processLists"
              :key="index"
            >
              <view>
                <text class="mgr">审批人:{{ item.username }}</text>
                <text class="mgr"
                  >环节:{{ item.wfOperationLogActivityName }}</text
                >
              </view>
              <view>
                <text>意见:{{ item.wfOperationLogHandleSuggestion }}</text>
                <text>日期:{{ item.wfOperationLogOperationTime }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view v-if="current === 1">
      <view
        class="overClass"
        style="height: 78vh"
        v-if="memberStore.stateTable.rows.length"
      >
        <view v-for="item in memberStore.stateTable.rows" :key="item.id">
          <view class="wrapBox">
            <view class="smallBox">
              <text class="maxwidth"> 危废行业俗称:{{ item.wfTypeName }} </text>
              <text> 容器/包装类型:{{ item.wfContainerType }} </text>
            </view>
            <view class="smallBox">
              <text> 产出日期:{{ item.create_Time }} </text>
              <text> 登记人:{{ item.registrant }} </text>
            </view>
            <view class="smallBox">
              <!-- <text> 名称:{{ item.wfName }} </text> -->
              <text> 去向:{{ item.wfTo }} </text>
            </view>
            <!-- <view class="smallBox">
              <text> 单位:{{ item.wfUnit }} </text>
              <text> 产出量:{{ item.wfWeight }} </text>
            </view> -->
            <!-- <view class="smallBox">
              <text> 废物类别:{{ item.wfTypeCode }} </text>
              <text> 危废代码:{{ item.wfCreateCode }} </text>
            </view> -->
          </view>
        </view>
      </view>
      <view class="wuClass" v-else>
        <view>暂无数据</view>
      </view>
    </view>
    <view
      class="flexClass"
      v-if="props.transStatus == 4 || props.fromPage == 'homePage'"
    >
      <button
        @tap="onSubmit(4)"
        class="form-button"
        style="margin-right: 20rpx"
        :disabled="disabled1"
        :loading="disabled1"
      >
        保存并退出
      </button>
      <button
        @tap="onSubmit(1)"
        class="form-button"
        :disabled="disabled2"
        :loading="disabled2"
      >
        保存并提交
      </button>
    </view>
    <view class="editApplication">
      <l-popup :radius="20" :show="popupShow">
        <view>
          <WasteCategories
            v-if="popupShow && componentName == 'WasteCategories'"
            @close="close"
            :flag="true"
            :wfType="`${memberStore.ApplyViewing.wfType}`"
            :wfTypeName="memberStore.ApplyViewing.wfTypeName"
            from="ApplicationDetails"
          ></WasteCategories>
          <depLists
            v-if="popupShow && componentName == 'depLists'"
            @close="close"
            :deptId="memberStore.ApplyViewing.applyDeptId"
          ></depLists>
        </view>
      </l-popup>
    </view>
  </view>
</template>

<script setup>
import {
  select_user_by_ids,
  select_flow_detail,
  wfTypeFindPage,
  select_register_by_ids,
  wfTransApplysaveOrUpdate,
  wfTransApplyUpdate,
  wf_flow_submit,
  update_register_status,
} from "@/commonApi";
import { parseTime, getCurrentTime, currentDate } from "@/utils";
import { useMemberStore } from "@/stores/modules/member";
const props = defineProps(["transStatus", "fromPage"]);
const picturesPath = ref([]);
const disabled1 = ref(false);
const disabled2 = ref(false);
const current = ref(0);
const items = ref(["基本信息", "转运详情"]);
const styleType = ref("button");
const activeColor = ref("#007aff");
const memberStore = useMemberStore();
const processLists = ref([]);
const heightRef = ref("78vh");
const popupShow = ref(false);
const componentName = ref("");
const handleTap = () => {
  if (props.transStatus == 4 || props.fromPage == "homePage") {
    popupShow.value = true;
    componentName.value = "WasteCategories";
  }
};
const handleDep = () => {
  if (props.transStatus == 4 || props.fromPage == "homePage") {
    if (memberStore.deptMap.length > 1) {
      popupShow.value = true;
      componentName.value = "depLists";
    }
  }
};
let proids = "";
onLoad(async () => {
  if (props.transStatus == 4 || props.fromPage == "homePage") {
    heightRef.value = "78vh";
    uni.setNavigationBarTitle({
      title: "申请转运编辑",
    });
  } else {
    heightRef.value = "89vh";
    uni.setNavigationBarTitle({
      title: "申请转运查看",
    });
  }

  proids = memberStore.ApplyViewing.wfIds;
  memberStore.typeAndDep = {};
  memberStore.stateTable.rows = [];
  if (memberStore.ApplyViewing.picture) {
    picturesPath.value = JSON.parse(memberStore.ApplyViewing.picture);
  }
  const res = await select_register_by_ids(memberStore.ApplyViewing.wfIds);

  memberStore.stateTable.rows = JSON.parse(JSON.stringify(res.data));
  const ress = await wfTypeFindPage();
  const createUserIds = memberStore.stateTable.rows.map(
    (item) => item.createUserId
  );
  const idsStr1 = [...new Set(createUserIds)].join();
  const resids = await select_user_by_ids(idsStr1);
  memberStore.stateTable.rows.forEach((item) => {
    item.create_Time = parseTime(item.produceTime, "{y}-{m}-{d}");
    const obj1 = resids.data.find((list) => list.userId == item.createUserId);
    if (obj1) {
      item.registrant = obj1.username;
    }
    //获取危废行业俗称
    if (item.wfType) {
      const typeLists = item.wfType.split(",");
      const TypeNames = [];
      typeLists.forEach((wfType) => {
        const obj1 = ress.data.find((item) => item.id == wfType);
        if (obj1) {
          TypeNames.push(obj1.wfTypeName);
        }
      });
      item.wfTypeName = TypeNames.join(",");
    }
    //获取危废行业俗称
  });
  memberStore.stateTable.temporaryData = JSON.parse(
    JSON.stringify(memberStore.stateTable.rows)
  );
  //获取危废行业俗称
  const typeLists = memberStore.ApplyViewing.wfType.split(",");
  const TypeNames = [];
  typeLists.forEach((wfType) => {
    const obj1 = ress.data.find((item) => item.id == wfType);
    if (obj1) {
      TypeNames.push(obj1.wfTypeName);
    }
  });
  memberStore.ApplyViewing.wfTypeName = TypeNames.join(",");
  //获取危废行业俗称
  const obj2 = memberStore.deptMap.find(
    (item) => item.deptId == memberStore.ApplyViewing.applyDeptId
  );
  if (obj2) {
    memberStore.ApplyViewing.deptName = obj2.name;
  }
  const result = await select_flow_detail(
    memberStore.ApplyViewing.flowInstanceId
  );
  processLists.value = JSON.parse(JSON.stringify(result.data));
  const ids = processLists.value.map((item) => item.wfOperationLogUserId);
  const filterIds = [...new Set(ids)].join();
  const res1 = await select_user_by_ids(filterIds);
  processLists.value.forEach((item) => {
    const obj = res1.data.find(
      (list) => list.userId == item.wfOperationLogUserId
    );
    if (obj) {
      item.username = obj.username;
    }
    item.wfOperationLogOperationTime = parseTime(
      item.wfOperationLogOperationTime
    );
  });
});
const close = () => {
  popupShow.value = false;
  if (componentName.value == "WasteCategories") {
    memberStore.ApplyViewing.wfTypeName = memberStore.typeAndDep.wfTypeName;
    memberStore.ApplyViewing.wfType = memberStore.typeAndDep.id;
  } else {
    memberStore.ApplyViewing.applyDeptId = memberStore.typeAndDep.deptId;
    memberStore.ApplyViewing.deptName = memberStore.typeAndDep.name;
  }
};
const onClickItem = (e) => {
  if (current.value !== e.currentIndex) {
    current.value = e.currentIndex;
  }
};
const handlezhuanyun = () => {
  if (
    memberStore.ApplyViewing.wfTypeName &&
    memberStore.ApplyViewing.deptName
  ) {
    uni.navigateTo({
      url: `/pages/wasteRegistration/wasteRegistration?wftype=${memberStore.ApplyViewing.wfType}&applyDeptId=${memberStore.ApplyViewing.applyDeptId}&from=ApplicationDetails`,
    });
  } else {
    uni.showToast({
      icon: "none",
      title: "请选择危废行业俗称和所属部门",
    });
  }
};

// 点击保存提交表单
const onSubmit = async (transStatus) => {
  if (!memberStore.ApplyViewing.wfTypeName) {
    return uni.showToast({
      icon: "none",
      title: "危废行业俗称不能为空",
    });
  }
  if (!memberStore.ApplyViewing.deptName) {
    return uni.showToast({
      icon: "none",
      title: "所属部门不能为空",
    });
  }
  if (!memberStore.ApplyViewing.planTransTime) {
    return uni.showToast({
      icon: "none",
      title: "转移时间不能为空",
    });
  }
  if (!memberStore.ApplyViewing.wfIds) {
    return uni.showToast({
      icon: "none",
      title: "转运详情不能为空",
    });
  }
  if (!memberStore.ApplyViewing.transTo) {
    return uni.showToast({
      icon: "none",
      title: "去向不能为空",
    });
  }
  if (!picturesPath.value.length) {
    return uni.showToast({
      icon: "none",
      title: "上传附件不能为空",
    });
  }

  const wfTypeNames = memberStore.ApplyViewing.wfTypeName.split(",");
  const names = wfTypeNames.reduce((pre, wfTypeName) => {
    const flag = memberStore.stateTable.rows.find(
      (list) => list.wfTypeName == wfTypeName
    );
    if (!flag) {
      pre.push(wfTypeName);
    }
    return pre;
  }, []);
  if (names.length) {
    return uni.showToast({
      icon: "none",
      title: `请删除危废行业俗称中的’${names.join(",")}‘`,
      duration: 3000,
    });
  }
  memberStore.ApplyViewing.transStatus = transStatus;
  memberStore.ApplyViewing.applyUserId = memberStore.userId;
  memberStore.ApplyViewing.submitTime = getCurrentTime();
  memberStore.ApplyViewing.picture = JSON.stringify(picturesPath.value);
  try {
    if (transStatus == 4) {
      disabled1.value = true;
    } else {
      disabled2.value = true;
    }
    if (props.fromPage == "homePage") {
      memberStore.ApplyViewing.transStatus = 1;
      await wfTransApplyUpdate(memberStore.ApplyViewing);
      if (transStatus == 1) {
        await wf_flow_submit(
          memberStore.ApplyViewing.applyId,
          memberStore.ApplyViewing.workitemId,
          memberStore.ApplyViewing.applyDeptId
        );
      }
    } else {
      await wfTransApplysaveOrUpdate(memberStore.ApplyViewing);
    }
    const registerStatus =
      props.fromPage == "homePage" ? 2 : transStatus == 4 ? 4 : 2;
    if (proids != memberStore.ApplyViewing.wfIds) {
      const oldIds = proids.split(",");
      const newIds = memberStore.ApplyViewing.wfIds.split(",");
      const isSamedata = oldIds.some((item) => newIds.includes(item));
      if (isSamedata) {
        if (oldIds.length != newIds.length) {
          const sameSData = [];
          const deleteData = [];
          oldIds.forEach((item) => {
            if (newIds.includes(item)) {
              sameSData.push(item);
            } else {
              deleteData.push(item);
            }
          });
          if (oldIds.length > newIds.length) {
            update_register_status(deleteData.join(), 1);
            update_register_status(
              memberStore.ApplyViewing.wfIds,
              registerStatus
            );
          } else {
            if (deleteData.join()) {
              update_register_status(deleteData.join(), 1);
              update_register_status(
                memberStore.ApplyViewing.wfIds,
                registerStatus
              );
            } else {
              update_register_status(
                memberStore.ApplyViewing.wfIds,
                registerStatus
              );
            }
          }
        } else {
          const sameSData = [];
          const deleteData = [];
          oldIds.forEach((item) => {
            if (newIds.includes(item)) {
              sameSData.push(item);
            } else {
              deleteData.push(item);
            }
          });
          if (deleteData.join()) {
            update_register_status(deleteData.join(), 1);
            update_register_status(
              memberStore.ApplyViewing.wfIds,
              registerStatus
            );
          } else {
            update_register_status(proids, registerStatus);
          }
        }
      } else {
        update_register_status(proids, 1);
        update_register_status(memberStore.ApplyViewing.wfIds, registerStatus);
      }
    } else {
      update_register_status(proids, registerStatus);
    }
    uni.showToast({ icon: "success", title: "操作成功" });
    setTimeout(() => {
      uni.navigateBack({ delta: 1 });
    }, 400);
  } finally {
    if (transStatus == 4) {
      disabled1.value = false;
    } else {
      disabled2.value = false;
    }
  }
};
const handledate = () => {
  if (props.transStatus == 4 || props.fromPage == "homePage") {
    dd.datePicker({
      format: "yyyy-MM-dd",
      success: (res) => {
        memberStore.ApplyViewing.planTransTime = res.date.replaceAll("/", "-");
        if (
          new Date(memberStore.ApplyViewing.planTransTime).getTime() <
          currentDate()
        ) {
          memberStore.ApplyViewing.planTransTime = "";
          uni.showToast({
            icon: "none",
            title: "请选择当天及以后的日期",
          });
        }
      },
      fail: (err) => {},
    });
  }
};
</script>

<style lang="scss" scoped>
.form {
  background-color: #f4f4f4;
  .form-content {
    height: v-bind(heightRef);
    overflow-y: auto;
  }
  &-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 96rpx;
    line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
    }

    .label {
      // width: 180rpx;
      white-space: nowrap;
      padding-right: 5rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }
    .placeholder {
      color: #808080;
    }
  }

  // &-button {
  //   height: 80rpx;
  //   text-align: center;
  //   line-height: 80rpx;
  //   margin: 30rpx 20rpx;
  //   color: #fff;
  //   border-radius: 80rpx;
  //   font-size: 30rpx;
  //   background-color: #27ba9b;
  //   position: fixed;
  //   bottom: 40rpx;
  //   width: 90%;
  // }
}

.flexClass {
  display: flex;
  justify-content: center;
  padding-top: 30rpx;
  .form-button {
    width: 40%;
    background-color: rgb(0, 122, 255);
    border-radius: 10rpx;
    color: white;
  }
}
.liucheng {
  display: flex;
  justify-content: space-around;
}
.wuClass {
  height: 78vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: rgb(0, 122, 255);
  // font-size: 40rpx;
}
.listsClass {
  line-height: 46rpx;
  padding: 25rpx 10rpx;
  background-color: #fff;
  font-size: 28rpx;
  border-bottom: 1rpx solid #ddd;
  view {
    display: flex;
    justify-content: space-between;
  }
}
.scrollClass {
  // height: 80vh;
  // overflow-y: auto;
}
</style>